package gps.methods.ida_star;

import gps.Node;
import gps.methods.BaseMethod;
import gps.methods.BaseNode;
import gps_api.Problem;
import gps_api.Rule;
import gps_api.State;

public class IdaStarMethod extends BaseMethod{
	Problem problem;
	Double fMin;

	public IdaStarMethod(Problem problem){
		this.problem= problem;
		this.fMin=0.0;
	}
	
	@Override
	public void addChild(State state, Rule rule) {	
		Node node= new BaseNode(lastNode, state, rule, rule.getCost(),problem.getHeuristic(state));
		if(!isInOpenedList(node)){
			openedNodes.addFirst(node);	
		}
		
	}

	@Override
	public Node getNextNode() {
		boolean ans=false;
		int minIndex=0;	
		
		for (int i=0; i<openedNodes.size() && !ans; i++) {
			if(openedNodes.get(i).getF()<= fMin){
				lastNode= openedNodes.remove(i);
				ans=true;
			}else if(openedNodes.get(i).getF()<openedNodes.get(minIndex).getF()){
				minIndex=i;
			}
		}
		
		if(!ans){
			lastNode=openedNodes.remove(minIndex);
			fMin= lastNode.getF();
		}
		
		closedNodes.add(lastNode);
		setMaxlevel();
		
		return lastNode;
		
	}

}
